package hit.edu.zjc.Tool;

import hit.edu.zjc.DataIntegration.DBConInfo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DataBaseTool
{
	
	public Connection con=null;
	public Statement stm=null;
 	public boolean connected()
	{
		if(con==null||stm==null)
			return false;
		return true;
	}
	public ResultSet exesql(String str)
	{
		try
		{
			//Statement stm=con.createStatement();
			ResultSet rs=stm.executeQuery(str);
			return rs;
		}
		catch(SQLException exp)
		{
			exp.printStackTrace();
			return null;
		}
	}
	public boolean exeupdate(String str)
	{
		try
		{
			//Statement stm=con.createStatement();
			stm.executeUpdate(str);
			return true;
		}
		catch(SQLException exp)
		{
			exp.printStackTrace();
			return false;
		}
	}
	public void close()
	{
		if(con!=null)
		{
			try
			{
				con.close();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			finally
			{
				con=null;
			}
		}
		if(stm!=null)
		{
			try
			{
				stm.close();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			finally
			{
				stm=null;
			}
		}
	}
	
	public DataBaseTool()
	{
		try
		{
			Class.forName("com.mysql.jdbc.Driver");
			con=DriverManager.getConnection("jdbc:mysql://192.168.59.1:3306/mydb","root","zhangxu");
			stm=con.createStatement();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	public DataBaseTool(String dbip,String dbport,String dbname,String username,String password,int dbtype)
	{
		if(dbtype==DBConInfo.TYPE_MYSQL)
		{
			try
			{
				Class.forName("com.mysql.jdbc.Driver");
				con=DriverManager.getConnection("jdbc:mysql://"+dbip+":"+dbport+"/"+dbname+"?zeroDateTimeBehavior=round",username,password);
				stm=con.createStatement();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		else if(dbtype==DBConInfo.TYPE_MSSQL)
		{
			try
			{
				Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
				con=DriverManager.getConnection("jdbc:sqlserver://"+dbip+":"+dbport+";DatabaseName="+dbname,username,password);
				stm=con.createStatement();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	}
	public DataBaseTool(DBConInfo dbci)
	{
		   this(dbci.dbip,dbci.dbport,dbci.dbname,dbci.username,dbci.password,dbci.dbtype);		
	}


}
